package servlet;

import hibernate.User;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.GetMenuInfoDAO;

/**
 * Servlet implementation class loginServlet
 */
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @param session 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		session.setAttribute("userName",null);
		PrintWriter out = response.getWriter();
        GetMenuInfoDAO getUserInfo = new GetMenuInfoDAO();
		List userInfo = getUserInfo.validateUser(userName,password);
		if(userInfo.size() == 0)
			out.print("{success:false,msg:'The user name and password combination you entered does not correspond to a registered user.'}");
		else{
			for(int i=0; i<userInfo.size(); i++){
			    User user = (User)userInfo.get(i);
			    String name = user.getUserName();
			    String trueN = user.getTrueName();
			    if(session.getAttribute("userName") == null){
			        session.setAttribute("userName",name);
			        session.setAttribute("trueName",trueN);
			        session.setAttribute("role", 1);
			    }
			}
			out.print("{success:true,msg:'成功'}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
